package com.blb.day19_shiro.realm;

import com.blb.day19_shiro.entity.User;
import com.blb.day19_shiro.service.IUserService;
import com.blb.day19_shiro.service.impl.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 自定义Realm
 * AuthorizingRealm 需要实现验证和授权
 */
public class MyRealm extends AuthorizingRealm {

    private IUserService userService = new UserServiceImpl();

    //获得授权信息（角色和权限）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获得用户对象，SimpleAuthenticationInfo的第一参数
        User user = (User) principalCollection.getPrimaryPrincipal();
        //通过用户查询角色和权限
        System.out.println(user);
        //创建授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加角色
        info.addRole("admin");
        info.addRole("test");
        //添加权限
        info.addStringPermission("user:list");
        info.addStringPermission("user:insert");
        info.addStringPermission("user:update");
        info.addStringPermission("user:delete");
        return info;
    }

    //获得验证信息（登录）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获得输入账号和密码
        String username = authenticationToken.getPrincipal().toString();
        String password = authenticationToken.getCredentials().toString();
        System.out.println("username:"+username+" password:"+password);
        //通过用户名查询用户
        User user = userService.findUserByUsername(username);
        if(user == null){
            throw new UnknownAccountException("用户不存在");
        }
        //验证信息对象 参数1 用户名或用户对象 参数2 数据库中用户的密码 参数3 盐 参数4 Realm的名字
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getUsername()),getName());
    }
}
